﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using CoreLibrary.JsonNet;
using RestSharp;

namespace CoreLibrary.Email.Impl.Mandrill {

    public class MandrillAPI {

        private readonly RestClient _client;
        public IMandrillConfig Configuration { get; set; }

        public MandrillAPI(IMandrillConfig config, bool ssl = true) {
            Configuration = config;
            _client = ssl ? new RestClient(Configuration.RemoteSecureEndpoint)
                          : new RestClient(Configuration.RemoteEndpoint);
        }

        public List<MailResult> Send(Mail message, DateTime dateSent) {
            dynamic payload = new ExpandoObject();
            payload.message = message;
            return Post<List<MailResult>>(Configuration.MailEndpoint,
                   payload
            );
        }

        protected T Post<T>(string path, dynamic data) where T : new() {
            Asserts.NotNull (data, "Post data should not be null.");
            Asserts.NotBlank(path, "Email send point should not be null.");

            var restRequest = new RestRequest(path, Method.POST) {
                RequestFormat = DataFormat.Json
            };

            data.key = Configuration.ApiKey;
            restRequest.AddBody(data);

            var response = _client.Execute(restRequest);
            if (response.StatusCode == HttpStatusCode.OK) {
                return JSON.Deserialize<T>(response.Content);
            }

            ErrorMessage errorMessage;
            var parsed = JSON.TryDeserialize(response.Content, out errorMessage);
            if (parsed) {
                throw new Exception(errorMessage.ToString());
            }

            if (response.ErrorException != null) {
                throw new Exception(response.ErrorException.Message);
            }

            throw new Exception("Unknow Email Error.");
        }
       
    }

}